//
//  ZFMDBDao.swift
//  swift-weibo
//
//  Created by zero on 17/4/2.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit
import FMDB

class ZFMDBDao{

    //  创建单例对象
    static let share:ZFMDBDao = ZFMDBDao()
    
    //  创建数据库操作对象
    let queue:FMDatabaseQueue
    
    init() {
     
        let path = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("weibo.db")
        
        queue = FMDatabaseQueue(path: path)
        
    }
    
    
}

//MARK:查询获得一个字典数组

extension ZFMDBDao{

    func selectedData(sqlString:String) -> [[String:Any]]{
        
        
        //  创建一个可变的字典数组
        var tempArray:[[String:Any]] = [[String:Any]]()
        
        //  定一个可变的数组
        ZFMDBDao.share.queue.inDatabase { (db) in
            
            let res = db?.executeQuery(sqlString, withArgumentsIn: nil)
            
            while res!.next(){
                
                //  创建一个可变的字典
                var dict:[String:Any] = [String:Any]()
                
                //  遍历
                for i in 0..<res!.columnCount(){
                    
                    let key = res?.columnName(for: i)
                    let value = res?.object(forColumnName: key)
                    
                    dict[key!] = value
                    
                }
                
                tempArray.append(dict)
            }
        }
        
        
        return tempArray
    }
    
}
